package com.orhon.smartcampus.modules.teacher.fetcher;

import java.util.List;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.teacher.dao.LearningExperienceDao;
import com.orhon.smartcampus.modules.teacher.entity.LearningExperience;
import com.orhon.smartcampus.modules.teacher.gqlModel.GQLLearningExperience;
import com.orhon.smartcampus.modules.teacher.mm.LearningExperienceMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class LearningExperiencesFetcher implements DataFetcher {
	
	@Autowired
	LearningExperienceDao learningExperienceDao;

	@Autowired
	TokenService tokenService;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {

		String token = tokenService.getSystemToken();
		if(token==null) {
			return  R.NoLogin();
		}
		Long schoolId = JwtUtils.getSchoolId(token);

		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
		String hql = "from LearningExperience where deleted_at = null and school_id = " + schoolId;
		if(env.getArgument("teacher_id")!=null) {
			int id = Integer.parseInt(env.getArgument("teacher_id").toString());
			hql += " and teacher_id = " + id;
		}
		List<LearningExperience> list = learningExperienceDao.find(hql,null,page.getPage(),page.getLimit());

		List<GQLLearningExperience> mapEntityList = LearningExperienceMapper.MAPPER.mapEntityList(list);

		Long total = 0L;
		if (env.getSelectionSet().contains("total")){
			total = learningExperienceDao.getTotalCount(hql);
		}
		return Result.ok().put("data", mapEntityList).put("total", total);
	}
}
